package com.aaa.order.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/11/21 9:19
 * @description：自定义微服务策略
 * @modified By：
 * @version:
 */
public class MyRule extends AbstractLoadBalancerRule {


    //统计访问的次数
    private int total;
    //作为集群服务器下标
    private int index;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        //获取负载均衡选择器
        ILoadBalancer lb = getLoadBalancer();
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            //获取所有可用的服务器
            List<Server> upList = lb.getReachableServers();
            //获取所有的服务器。
            List<Server> allList = lb.getAllServers();

            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }

            //判断该服务访问的次数是否>5次
            if(total<5){
                server=upList.get(index);
                total++;
            }else{
                total=0;
                index++;
                index=index%upList.size();
            }

            if (server == null) {
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }

            // Shouldn't actually happen.. but must be transient or a bug.
            server = null;
            Thread.yield();
        }

        return server;
    }

}